package com.xiaxiang.xiawan.My;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dg.acb.utils.configdata.XXConstants;
import com.okhttp.MyHttpUtils;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.service.DownloadService;
import com.xiaxiang.xiawan.My.Net.OkGoUpdateHttpUtil;
import com.xiaxiang.xiawan.NetBean.UpdateNetBean;
import com.xiaxiang.xiawan.R;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.JSON.MyJsonUtil;
import com.xiaxiang.xiawan.XXMainApplication;

public class SettingActivity extends AppCompatActivity {
    private  String title = "设置";
    private XXMainApplication app;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_setting);
        initTitle();
        setListener();
        app = XXMainApplication.getInstance();
        token = app.getToken();
    }

    private void setListener() {
        findViewById(R.id.checkUpdate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkUpdate();
            }
        });
        findViewById(R.id.btnLoginOut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyHttpUtils myHttpUtils = new MyHttpUtils();
                try {
                    myHttpUtils.PostCommonAsync(XXConstants.URI_URI_LOGIN_OUT,"",token, new MyHttpUtils.IMyHttpUtilsCallback() {
                        @Override
                        public void onFailure(String errorMsg) {
                            Log.i("Logout", errorMsg);
                            showToastTips("网络异常！");
                        }

                        @Override
                        public void onResponse(String response) {
                            showToastTips("退出成功！");
                            Log.i("Logout", response);
                            app.logout();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void checkUpdate() {
        String mUpdateUrl = XXConstants.URI_GET_VERSION;
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        Map<String, String> params = new HashMap<String, String>();

        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(mUpdateUrl)

                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(false)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
//                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")

                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        Log.i("drj", json);
                        UpdateNetBean updateNetBean = MyJsonUtil.parseObject(json, UpdateNetBean.class);
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        if (updateAppBean != null) {
                            updateAppBean
                                    //（必须）YES,NO
                                    .setUpdate(updateNetBean.getContent().getUpdate())
                                    //（必须）新版本号，
                                    .setNewVersion(updateNetBean.getContent().getNewVersion())
                                    //（必须）下载地址
                                    .setApkFileUrl(updateNetBean.getContent().getApkFileUrl())
                                    //（必须）更新内容
                                    .setUpdateLog(updateNetBean.getContent().getUpdateLog())
                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(updateNetBean.getContent().getTargetSize())
                                    //是否强制更新，可以不设置
                                    .setConstraint(false)
                                    //设置md5，可以不设置
                                    .setNewMd5(updateNetBean.getContent().getNewMd5());
                        }
                        return updateAppBean;
                    }

                    /**
                     * 有新版本
                     *
                     * @param updateApp        新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        //强制更新，
                        if (updateApp.isConstraint()) {

                        } else {

                        }
                        //自定义对话框
                        showDiyDialog(updateApp, updateAppManager);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
//                        CProgressDialogUtils.showProgressDialog(JavaActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
//                        CProgressDialogUtils.cancelProgressDialog(JavaActivity.this);
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                        Toast.makeText(getActivity(), "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void showDiyDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager) {
        String targetSize = updateApp.getTargetSize();
        String updateLog = updateApp.getUpdateLog();

        String msg = "";

        if (!TextUtils.isEmpty(targetSize)) {
            msg = "新版本大小：" + targetSize + "\n\n";
        }

        if (!TextUtils.isEmpty(updateLog)) {
            msg += updateLog;
        }

        new AlertDialog.Builder(this)
                .setTitle(String.format("是否升级到%s版本？", updateApp.getNewVersion()))
                .setMessage(msg)
                .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updateAppManager.download(new DownloadService.DownloadCallback() {
                            @Override
                            public void onStart() {
//                                    HProgressDialogUtils.showHorizontalProgressDialog(getActivity(), "下载进度", false);
                            }

                            /**
                             * 进度
                             *
                             * @param progress  进度 0.00 -1.00 ，总大小
                             * @param totalSize 总大小 单位B
                             */
                            @Override
                            public void onProgress(float progress, long totalSize) {
//                                    HProgressDialogUtils.setProgress(Math.round(progress * 100));
                            }

                            /**
                             *
                             * @param total 总大小 单位B
                             */
                            @Override
                            public void setMax(long total) {

                            }


                            @Override
                            public boolean onFinish(File file) {
//                                    HProgressDialogUtils.cancel();
                                return true;
                            }

                            @Override
                            public void onError(String msg) {
                                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
//                                    HProgressDialogUtils.cancel();
                            }
                        });

                        dialog.dismiss();
                    }
                })
                .setNegativeButton("暂不升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void initTitle() {
        ((TextView) findViewById(R.id.TitleBarText)).setText(title);
        ImageView back = (ImageView) findViewById(R.id.TitleBarLeftImg);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public Activity getActivity() {
        return this;
    }

    protected void showToastTips(final String tips) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast mToast = Toast.makeText(getActivity(), tips, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }
}
